/*
   Copyright 2012 Harri Smatt

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
 */

package com.swtplayer;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.androidquery.AQuery;
import com.androidquery.callback.AjaxCallback;
import com.androidquery.callback.AjaxStatus;
import com.androidquery.callback.BitmapAjaxCallback;
import com.androidquery.util.AQUtility;
import com.common.AreaListViewClick;
import com.common.MyApp;
import com.common.Video;
import com.readystatesoftware.viewbadger.BadgeView;
import com.widget.ezine.CurlPage;
import com.widget.ezine.CurlView;
import com.swtplayer.R;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.util.Log;
import android.view.GestureDetector;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.view.animation.Animation;
import android.widget.ImageView;

/**
 * Simple Activity for curl testing.
 * 
 * @author harism
 */
public class EzineActivity extends Activity {

	private CurlView mCurlView;
	AQuery aq = new AQuery(EzineActivity.this);
	MyApp _app=MyApp.getInstance(this);
	int mcurrent=0;
	public static List<String> ezinepage=new ArrayList<String>();
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.ezine);
		_app.addActivity(this);
		
		initContent();
		 
		// This is something somewhat experimental. Before uncommenting next
		// line, please see method comments in CurlView.
		// mCurlView.setEnableTouchPressure(true);
	}

	
	public void initContent()
	{
		int index = 0;
		if (getLastNonConfigurationInstance() != null) {
			index = (Integer) getLastNonConfigurationInstance();
		}
		
		
		long expire = 30 * 24 * 60 * 1000; 
		Intent intent = getIntent();
		String vid = intent.getStringExtra("vid");
		String showezinelist=intent.getStringExtra("showezinelist");
	    Video video = _app.allvList.get(vid);
	    final String siteDomain=getString(R.string.SITE_URL);
	    String ezineid=video.ezineid;
	    if(showezinelist!=null && showezinelist.equals("1"))
	    {
	    	if(video.ezineList!=null && video.ezineList.size()>0)
	    	{
	    	    ezineid=video.ezineList.get(0);
	    	    
	    	}
	    	else {
	    		 
	    		ezineid="";
			}
	    }
	    List<String> getezineList=_app.allezine.get(ezineid);
	    ezinepage=new ArrayList<String>();
	    if(getezineList!=null && getezineList.size()>0)
	    {
	    	 ezinepage.addAll(getezineList);
	    }
	    else {	    
	    AQuery aq =new AQuery(this);
		aq.ajax(siteDomain+"/ajax.aspx?action=getvideojson&type=getezinebyid&id="+ezineid, JSONObject.class, 1000,new AjaxCallback<JSONObject>(){
			
			 @Override 
		        public void callback(String url, JSONObject json, AjaxStatus status) { 
		                
				 try {
					 
					JSONArray pages = json.getJSONArray("pages");
					for (int i = 0; i < pages.length(); i++) {
						JSONObject item = ((JSONObject) pages.opt(i));
						ezinepage.add(siteDomain+item.getString("bigimg"));
					}
					 
					
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
		            
		        } 

		} );
		
		}
		mCurlView = (CurlView) findViewById(R.id.curl);
		mCurlView.setPageProvider(new PageProvider());
		mCurlView.setSizeChangedObserver(new SizeChangedObserver());
		mCurlView.setCurrentIndex(index);
		mCurlView.setBackgroundColor(0xFF202830);
		
		if (ezinepage.size() > 0) {
		BadgeView badge = new BadgeView(this, mCurlView);
		badge.setBackgroundResource(R.drawable.zoom);
		badge.setWidth(50);
		badge.setHeight(50);
		badge.setOnClickListener( new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent intent =new Intent();
		        intent.putExtra("url", ezinepage.get(mCurlView.getCurrentIndex()));
		        intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
		        intent.setClass(EzineActivity.this, ZoomActivity.class);
				startActivityForResult(intent,1);
			}
		});	
		int leftnum= (_app.GetScreenMetrics(this).widthPixels-50)/2;
		badge.setBadgeMargin(leftnum, 30);
		badge.setBadgePosition(com.readystatesoftware.viewbadger.BadgeView.POSITION_TOP_LEFT);
		badge.show();
		
		}
	
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		mCurlView.setCurrentIndex(mcurrent);		
		super.onActivityResult(requestCode, resultCode, data);
	}



	@Override
	public void onPause() {
		super.onPause();
		//mCurlView.onPause();
	}

	@Override
	public void onResume() {
		initContent();
		super.onResume();
		//mCurlView.onResume();
	}

	 
	
	
	@Override
	public Object onRetainNonConfigurationInstance() {
		return mCurlView.getCurrentIndex();
	}

	/**
	 * Bitmap provider.
	 */
	private class PageProvider implements CurlView.PageProvider {

		// Bitmap resources.
		private int[] mBitmapIds = { R.drawable.p1};
		
		 

		@Override
		public int getPageCount() {
			int num= ezinepage.size();
			if(num<1)
			{
				num=1;
			}
			return num;
		}

		private Bitmap loadBitmap(int width, int height, int index) {
			Bitmap b = Bitmap.createBitmap(width, height,
					Bitmap.Config.ARGB_8888);
			b.eraseColor(0xFFFFFFFF);
			Canvas c = new Canvas(b);
			Drawable d = getResources().getDrawable(mBitmapIds[index]);

			int margin = 7;
			int border = 3;
			Rect r = new Rect(margin, margin, width - margin, height - margin);

			int imageWidth = r.width() - (border * 2);
			int imageHeight = imageWidth * d.getIntrinsicHeight()
					/ d.getIntrinsicWidth();
			if (imageHeight > r.height() - (border * 2)) {
				imageHeight = r.height() - (border * 2);
				imageWidth = imageHeight * d.getIntrinsicWidth()
						/ d.getIntrinsicHeight();
			}

			r.left += ((r.width() - imageWidth) / 2) - border;
			r.right = r.left + imageWidth + border + border;
			r.top += ((r.height() - imageHeight) / 2) - border;
			r.bottom = r.top + imageHeight + border + border;

			Paint p = new Paint();
			p.setColor(0xFFC0C0C0);
			c.drawRect(r, p);
			r.left += border;
			r.right -= border;
			r.top += border;
			r.bottom -= border;

			d.setBounds(r);
			d.draw(c);

			return b;
		}

		@Override
		public void updatePage(CurlPage page, int width, int height, int index) {

			
			    final CurlPage f_page=page;
			    int num=index;
			    mcurrent=num;
			    int bg=index+1;
			    if(bg>=ezinepage.size())
			    {
			    	bg=ezinepage.size()-1;
			    }
			   
			    if(ezinepage.size()<1)
			    {
			    	Bitmap bm= loadBitmap(width,height,0);
			    	f_page.setTexture(bm, CurlPage.SIDE_FRONT);
			    	return;
			    }
			   
			    
			    aq.id(R.id.imgfront).image(ezinepage.get(num), true, true, 0, 0, new BitmapAjaxCallback(){

					@Override
					protected void callback(String url, ImageView iv,
							Bitmap bm, AjaxStatus status) {						     
						f_page.setTexture(bm, CurlPage.SIDE_FRONT);
						
					}		
			    });
			    
			    /*
			    aq.id(R.id.imgback).image(ezinepage.get(bg), true, true, 0, 0, new BitmapAjaxCallback(){
			    	@Override
					protected void callback(String url, ImageView iv,
							Bitmap bm, AjaxStatus status) {
			    		f_page.setTexture(bm, CurlPage.SIDE_BACK);
						 Log.w("AQuery", status.toString()+url);
					}
					
			    });
			    */
			   
			   
				
				//page.setColor(Color.argb(127, 170, 130, 255),CurlPage.SIDE_FRONT);
				//page.setColor(Color.rgb(255, 190, 150), CurlPage.SIDE_BACK);
				
			 
		}

		 
		
	}


 
	/**
	 * CurlView size changed observer.
	 */
	private class SizeChangedObserver implements CurlView.SizeChangedObserver {
		@Override
		public void onSizeChanged(int w, int h) {
			Boolean pagetype=false; //w > h;
			if (pagetype) {
				mCurlView.setViewMode(CurlView.SHOW_TWO_PAGES);
				mCurlView.setMargins(.1f, .05f, .1f, .05f);
			} else {
				mCurlView.setViewMode(CurlView.SHOW_ONE_PAGE);
				//mCurlView.setMargins(0f, 0f, 0f, 0f);
				mCurlView.setMargins(0f, 0f, 0f, 0f);
			}
		}
	}
	
	
	public boolean onOptionsItemSelected(MenuItem item) {
		boolean status = true;
		status=  _app.OptionsItemSelectedOpt(item);
		return status;
	}
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		getMenuInflater().inflate(R.menu.home_menu, menu);
		return true;
	}

}